package tw.idv.liuken.android.sip;

import tw.idv.liuken.android.sip.SimpleSessionDescription.Media;
import tw.idv.liuken.android.sip.rtp.VideoCodec;

public class SipVideoCall {
	private String mPeerSd;
	private VideoCodec mCodec;
	private int mVideoPort = 21070;
	
	public void setPeerSD(String sessionDescription) {
    	mPeerSd = sessionDescription;
    }
	
	public void startVideo() {
		
	}
	
	public Media createOffer(SimpleSessionDescription offer) {
		VideoCodec[] codecs = VideoCodec.getCodecs();
        Media media = offer.newMedia("video", mVideoPort, 1, "RTP/AVP");
        for (VideoCodec codec : VideoCodec.getCodecs()) {
            media.setRtpPayload(codec.type, codec.rtpmap, codec.fmtp);
        }
        
        return media;
    }
	
	public Media createAnswer(SimpleSessionDescription answer) {
        SimpleSessionDescription offer = new SimpleSessionDescription(mPeerSd);
        Media reply = null;

        VideoCodec codec = null;
        for (Media media : offer.getMedia()) {
        	if ("video".equals(media.getType())) { //Only checking video, audio is checked by SipAudioCall.
        		if ((codec == null) && (media.getPort() > 0) && "RTP/AVP".equals(media.getProtocol())) {
        			// Find the first video codec we supported.
        			for (int type : media.getRtpPayloadTypes()) {
        				codec = VideoCodec.getCodec(type, media.getRtpmap(type), media.getFmtp(type));
        				mCodec = codec;
        				if (codec != null) {
        					break;
        				}
        			}
        			if (codec != null) {
        				reply = answer.newMedia("video", mVideoPort, 1, "RTP/AVP");
        				reply.setRtpPayload(codec.type, codec.rtpmap, codec.fmtp);
        				continue;
        			}
        		}
            	// Reject the media.
            	reply = answer.newMedia(media.getType(), 0, 1, media.getProtocol());
            	for (String format : media.getFormats()) {
            		reply.setFormat(format, null);
            	}
        	}
        }
        if (codec == null) {
            throw new IllegalStateException("Reject SDP: no suitable codecs");
        }
        return reply;
    }

}
